import { Component, EventEmitter, Output, ViewChild } from '@angular/core';
import { ConfirmationService } from 'primeng/api';
import { FieldType } from 'src/components/scenarios/enums';
import { FieldMapConfig, FieldValueMap } from 'src/components/scenarios/models';
import { v4 as guid } from "uuid";
import { FieldValueMapConfigDialogComponent } from '../../field-value-map-config-dialog/field-value-map-config-dialog.component';

@Component({
  selector: 'app-field-map-setting-sidebar',
  templateUrl: './field-map-setting-sidebar.component.html',
  styleUrl: './field-map-setting-sidebar.component.scss'
})
export class FieldMapSettingSidebarComponent {

  visible: boolean = false;
  field!: FieldMapConfig;
  types: FieldType[] = Object.values(FieldType);

  @ViewChild("configDialog", { static: true })
  configDialog!: FieldValueMapConfigDialogComponent;

  @Output()
  editConfirm: EventEmitter<FieldMapConfig> = new EventEmitter();

  get canCommit() {
    const { Name, Type, Address } = this.field;
    return Name && Type && Address;
  }

  constructor(private confirmService: ConfirmationService) {
  }

  onShow(field: FieldMapConfig) {
    this.field = { ...field };
    this.visible = true;
  }

  onEditConfirm() {
    this.visible = false;
    this.editConfirm.next(this.field);
  }

  onEditCancel() {
    this.visible = false;
  }

  onAddFieldMapClick() {
    this.configDialog.onShow();
  }
  onEditFieldMap(map: FieldValueMap) {
    this.configDialog.onShow(map);
  }
  onDeleteFieldMap(map: FieldValueMap) {
    this.confirmService.confirm({
      message: '确定删除该记录?',
      header: '删除确认',
      icon: 'pi pi-info-circle',
      acceptButtonStyleClass: "p-button-danger p-button-text",
      rejectButtonStyleClass: "p-button-text p-button-text",
      acceptIcon: "none",
      rejectIcon: "none",
      accept: () => {
        this.field.Maps = this.field.Maps.filter(item => item.Id != map.Id);
      },
      reject: () => {
      }
    });
  }

  onEditFieldMapConfirm(status: FieldValueMap) {
    if (status.Id) {
      this.field.Maps = this.field.Maps.map(item => item.Id === status.Id ? status : item);
    } else {
      this.field.Maps.push({ ...status, Id: guid() });
    }
  }
}
